﻿/*****************************************************
 * 本类库的核心系 JNTemplate
 * (C) JNTemplate 2011
 * 作者：翅膀的初衷 QQ:4585839
 * 网址：http://www.JiNianNet.com
 *****************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

namespace JinianNet.JNTemplate.Process.Element {
    public class IfTag : CompositeTag {
        public IfTag(string text)
            : base(TokenKind.Function, text) {
            this._elseifcondition = new List<string>();
            this._ifelement = new List<Token>();
            this._elseifelement = new List<List<Token>>();
            this._elseelement = new List<Token>();
        }

        private string _ifcondition;
        public string IfCondition {
            get { return this._ifcondition; }
            set {
                if (value == null) {
                    this._ifcondition = string.Empty;
                }
                else {
                    this._ifcondition = value.Trim();
                }
            }
        }

        private List<string> _elseifcondition;
        public List<string> ElseIfCondition {
            get { return this._elseifcondition; }
            set {
                if (value == null) {
                    this._elseifcondition = new List<string>();
                }
                else {
                    this._elseifcondition = value;
                }
            }
        }

        private List<Token> _ifelement;
        public List<Token> IfElement {
            get { return this._ifelement; }
            set {
                if (value == null) {
                    this._ifelement = new List<Token>();
                }
                else {
                    this._ifelement = value;
                }
            }
        }

        private List<List<Token>> _elseifelement;
        public List<List<Token>> ElseIfElement {
            get { return this._elseifelement; }
            set {
                if (value == null) {
                    this._elseifelement = new List<List<Token>>();
                }
                else {
                    this._elseifelement = value;
                }
            }
        }

        private List<Token> _elseelement;
        public List<Token> ElseElement {
            get { return this._elseelement; }
            set {
                if (value == null) {
                    this._elseelement = new List<Token>();
                }
                else {
                    this._elseelement = value;
                }
            }
        }

        public override void Parser(VariableScope varScope, System.IO.TextWriter write) {
            if (this._elseifelement.Count != this._elseifcondition.Count && string.IsNullOrEmpty(this._ifcondition)) {
                write.Write("错误的IF标签");
                return;
            }
            else {
                if (Judgment(varScope, this._ifcondition)) {
                    if (this._ifelement.Count > 0) {
                        Parser(varScope,write, this._ifelement.ToArray());
                        return;
                    }
                }
                else {
                    if (this._elseifelement.Count > 0) {
                        for (int i = 0; i < this._elseifcondition.Count; i++) {
                            if (Judgment(varScope, this._elseifcondition[i])) {
                                Parser(varScope, write,this._elseifelement[i].ToArray());
                                return;
                            }
                        }
                    }
                    if (this._elseelement.Count > 0) {
                        Parser(varScope,write, this._elseelement.ToArray());
                        return;
                    }
                }
            }
        }

        private void Parser(VariableScope varScope, System.IO.TextWriter write,Token[] tokens) {
            foreach (Token token in tokens)
                write.Write(token.Parser(varScope));
        }

        private bool Judgment(VariableScope varScope, string expression) {
            if (expression != null && !string.IsNullOrEmpty(expression)) {
                if (expression.IndexOf(' ') != -1) {
                    expression = expression.Replace(" ", "");
                }
                if (expression == "1" || expression.Equals("true", StringComparison.OrdinalIgnoreCase)) {
                    return true;
                }
                if (expression == "0" || expression.Equals("false", StringComparison.OrdinalIgnoreCase)) {
                    return false;
                }
                if (expression.Contains(">") || expression.Contains("<") || expression.Contains("=")) {//必须存在> < == != >= <=

                    string[] list=new string[3];
                    if (expression.Contains(">=")) {
                        list[1] = ">=";
                    }else if (expression.Contains("<=")){
                        list[1] = "<=";
                    }
                    else if (expression.Contains("==")) {
                        list[1] = "==";
                    }
                    else if (expression.Contains("!=")) {
                        list[1] = "!=";
                    }
                    else if (expression.Contains(">")) {
                        list[1] = ">";
                    }
                    else if (expression.Contains("<")) {
                        list[1] = "<";
                    }
                    else {
                        throw new Exception("IF标签表达式错误");
                    }
                    int size = expression.IndexOf(list[1]);

                    list[0] = expression.Substring(0, size);
                    list[2] = expression.Substring(size + list[1].Length, expression.Length - (size + list[1].Length));
                    List<object> leftVar;
                    List<object> rightVar;

                    char[] charArray = new char[] { '+', '-', '*', '/', '%' };

                    TemplateParser parser = new TemplateParser();

                    leftVar = parser.Split(list[0], true, charArray);
                    rightVar = parser.Split(list[2], true, charArray);

                    for (int i = 0; i < leftVar.Count; i++) {
                        if (leftVar[i] is Token) {
                            leftVar[i] = ((Token)leftVar[i]).Parser(varScope);
                        }
                    }

                    for (int i = 0; i < rightVar.Count; i++) {
                        if (rightVar[i] is Token) {
                            rightVar[i] = ((Token)rightVar[i]).Parser(varScope);
                        }
                    }

                    string x = string.Concat(leftVar.ToArray());
                    string y = string.Concat(rightVar.ToArray());

                    if (leftVar.Count > 1) {
                        float fx; string sx;
                        if (Common.CalculatorHelper.Calculate(x, out fx, out sx)) {
                            x = fx.ToString();
                        }
                        else {
                            throw new Exception(sx);
                        }
                    }

                    if (rightVar.Count > 1) {
                        float fx; string sx;
                        if (Common.CalculatorHelper.Calculate(y, out fx, out sx)) {
                            y = fx.ToString();
                        }
                        else {
                            throw new Exception(sx);
                        }
                    }

                    return Parsing.CompareObject(x, y, list[1]);
                }
                else {
                    throw new Exception("IF标签表达式错误");
                }
            }
            return false;
        }
    }
}
